package com.sy.simpleegg.ext

import android.content.Context
import android.os.SystemClock
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.sy.simpleegg.widget.CustomToast
import com.sy.logger.Logger
import com.sy.simpleegg.app.App
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
import com.sy.simpleegg.BuildConfig
import com.sy.simpleegg.config.Config
import com.sy.simpleegg.constant.Constant
import com.sy.simpleegg.platform.BackstagePlatform
import com.sy.simpleegg.util.Preference


/**
 * 设备状态 true-正常 false-故障
 */
private var deviceStatus: Boolean by Preference(Constant.SETTING_DEVICE_STATUS, true)

fun Any.logFile(msg: String?){
    if (BuildConfig.DEBUG) {
        Log.e(this.javaClass.simpleName ?: App.TAG, msg ?: "")
    }
    Logger.d((this.javaClass.simpleName ?: App.TAG) + ":" + msg)
}

fun Any.getSettingPlatform(bsCode: Int): BackstagePlatform{
    BackstagePlatform.entries.forEach { bs ->
        if (bs.backstageCode == bsCode){
            return bs
        }
    }
    return BackstagePlatform.DEF_MQTT
}

fun showToastMsg(msg: String){
    CustomToast(App.instance, msg).show()
}

fun Context.showToastMsg(msg: String){
    CustomToast(this, msg).show()
}

fun Fragment.showToastMsg(msg: String){
    CustomToast(context, msg).show()
}

fun Fragment.countDown(
    time: Int,
    start: (scop: CoroutineScope) -> Unit,
    next: (time: Int) -> Unit,
    end: () -> Unit
){
    lifecycleScope.launch {
        // 在这个范围内启动的协程会在Lifecycle被销毁的时候自动取消

        flow {
            (time downTo 0).forEach {
                delay(1000)
                emit(it)
            }
        }.onStart {
            // 倒计时开始 ，在这里可以让Button 禁止点击状态
            start(this@launch)

        }.onCompletion {
            // 倒计时结束 ，在这里可以让Button 恢复点击状态
            end()

        }.catch {
            //错误
            logFile("${javaClass.simpleName} 倒计时异常：${it.message?:"Unkown Error"}")

        }.collect {
            // 在这里 更新值来显示到UI
            next(it)
        }

    }
}

fun View.onClick(gap: Long = 500L, block: () -> Unit){
    val listener = object : View.OnClickListener{
        var lastClickTime = 0L
        override fun onClick(v: View?) {
            val currentClickTime = SystemClock.elapsedRealtime()
            if (currentClickTime - lastClickTime > gap){
                lastClickTime = currentClickTime
                block.invoke()
            }
        }
    }
    setOnClickListener(listener)
}

fun Any.getDeviceStatus(): Boolean{
    return if (Config.ORDER_SUPPLEMENT){
        Config.DEVICE_STATUS
    }else{
        true
    }
}

fun Any.setDeviceStatus(status: Boolean){
    deviceStatus = status
    Config.DEVICE_STATUS = status
}